/*
 *  ufmail, a suite of mail servers
 *  Copyright (C) 2013  Jonathon Keogh
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 *  Jonathon Keogh e-mail: jdkeogh@live.com
 */

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include "log.h"

void writeToLog(unsigned short shType, const char *sMessage, ...) {
	va_list vArgs;
	char s[20], *s2;
	int i;

	// Prefix
	strcpy(s, "unknown");
	if(shType == LOG_INFO) {
		strcpy(s, "info");
	} else if(shType == LOG_ERROR) {
		strcpy(s, "error");
	}

	// How long is the message?
	va_start(vArgs, sMessage);
	i = vsnprintf(NULL, 0, sMessage, vArgs);
	va_end(vArgs);

	// Allocate memory
	s2 = malloc(i + 1);
	memset(s2, 0, i + 1);

	// Write to string
	va_start(vArgs, sMessage);
	vsprintf(s2, sMessage, vArgs);
	va_end(vArgs);

	// Write to file
	fprintf(fLog, "[DATE/TIME] %s: %s\n", s, s2); // TODO Date and time
	fflush(fLog);

	// Are we to write to the console too?
	if(shOutputLogToConsole == 1) {
		printf("%s: %s\n", s, s2);
	}

	// Clean up
	free(s2);
}
